<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
class Shop extends Controller
{

    public  function  _initialize()
    {

    }
  //向购物车里添加数据(id问题暂定，不确定返回的数据是不是ID号，并且不知道$re的值是不是常在)
  public function addFoodToCart($food_id,$shop_id,$num)
  {


          //http://localhost/CampusReservations/public/index.php/home/shop/addFoodToCart/food_id/5/shop_id/5/uid/2/num/1
    $uid=session('id');
      //$uid=10;
     if ($uid==null) {
         echo "您未登录，不能添加购物车，请登录！";
         return;
       }
          //$uid=session('id');
          $data=array();
          if($num==1&&$num!=0)
          {
           $data['food_id']=$food_id;
           $data['shop_id']=$shop_id;
           $data['user_id']=$uid;
           $data['num']=$num;
           $data['shoptime']=date("Y-m-d h:i:sa");
           $re=\think\Db::name('shopcart')->insert($data);
           if ($re) {
             echo "增加1";
           }
           else{
             echo "0";
           }
          }
         else
         {
         $data['num']=$num;
         //$data['shoptime']=date("Y-m-d h:i:sa");
         $res= \think\Db::name('shopcart')->where("user_id='$uid' AND food_id='$food_id'")->setInc('num');
         //echo \think\Db::name('shopcart')->getLastSql();
           if ($res) {
               echo "修改+1";
             }
             else{
               echo "增加失败";
             }
         }
  }


  //从购物车里删除数据(id问题暂定，不确定返回的数据是不是ID号，并且不知道$re的值是不是常在)
  public function subFoodToCart($food_id,$num)
  {
    //http://localhost/CampusReservations/public/index.php/home/shop/subFoodToCart/food_id/10/uid/10/num/4
       $uid=session('id');
      //$uid=10;
     if ($uid==null) {
         return;
       }
       //$uid=10;
       $data=array();
         if($num==0)
         {

           $re=\think\Db::name('shopcart')->where("user_id='$uid' AND food_id='$food_id'")->delete();
           if ($re) {
             echo "删除成功";
           }
           else{
             echo "删除失败";
           }
         }

       else
       {
        //  $data['shoptime']=date("Y-m-d h:i:sa");
        $res= \think\Db::name('shopcart')->where("user_id='$uid' AND food_id='$food_id'")->setDec('num');
        if ($res) {
               echo "true";
             }
             else{
               echo "减少失败";
             }
         }
  }
    // 餐厅列表
    public function lists()
    {
        
        //销量最高
        $topList=\think\Db::name('dining')
        ->alias('d')
        ->join('cr_order o','d.shop_id=o.shop_id')
        ->field('d.shopname,d.shop_id,d.pic')
        ->group('o.shop_id')
        ->order('sum(o.num) desc')
        ->limit(5)
        ->select();
        //店铺列表
        $shopList=\think\Db::name('dining')->order('createtime desc')->paginate(6);
        $page=$shopList->render();
        //新店入住
        $newshop = \think\Db::name('dining')->order('createtime desc')->limit(5)->select();
        $this->assign("page",$page);
         $this->assign("newshop",$newshop);
        $this->assign("shopList",$shopList);
        $this->assign("topList",$topList);
        return $this->fetch();
    }
    

    // 餐厅详情
     public function detail($shop_id)
    {
        $orderList=array();
        $sum=0;
        $tfood=array();
          //得到店铺ID
        $id=$shop_id;
        //店铺大图
        $shopPic= \think\Db::name("dining")->where("shop_id='$id'")->column("pic");
        $userInfo=array();
        //点击浏览店铺是点击率自增1
        \think\Db::name("dining")->where("shop_id='$id'")->setInc("obserave","1");
        //得到店铺详情
        $shopinfo= \think\Db::name('dining')->where("shop_id='$id'")->select();
        //得到评论列表   (注)：代码要修改，在显示有回复评论的同时，也要现在没有评论的
        $list=\think\Db::view('message','id,uid,did,mdate as messdate,message')
        ->view('reply','id,mid,mdate as rdate,message,uid,shopid','message.id=reply.mid')
        ->view('users','pic as upic,nickname','message.uid=users.id')
        ->view('dining','pic as dpic,shop_id,shopname',"dining.shop_id='$id'")
        ->where("message.did='$id'")
        ->order("message.mdate desc")
        ->select();
        //得到美食类别和类别下的美食
        $type=\think\Db::name('type')->where("shop_id='$id'")->select();
        //$num=\think\Db::name('type')->where("shop_id='$id'")->count();
        $count=0;
        //得到用户的session登陆信息 
      if (session('id')==null) {
        $uid=null;
        for ($i=0; $i <sizeof($type) ; $i++) { 
            $tid=$type[$i]['type_id']; 
             $sql1="
             select cr_food.shop_id,cr_food.food_id,cr_food.food_id=null num ,cr_food.pic,cr_food.price,cr_food.intro,cr_food.foodname from cr_food left join  cr_type on cr_food.type_id=cr_type.type_id AND cr_food.shop_id=cr_type.shop_id  where cr_type.type_id='$tid'";
             $tfood[$i]=\think\Db::name('')->query($sql1);
             
        } 

        $this->assign(array(
        "UUID"=>null,
        "userInfo"=>null,
        "shopFee1"=>null,
        "orderSum"=>null,
        "sum"=>null,
        "orderList"=>null
          ));
      }
      else
      {
         $uid=session('id');
          //根据session得到用户信息
         $userInfo=\think\Db::name('users')->where("id=$uid")->select();
          for ($i=0; $i <sizeof($type) ; $i++) { 
            $tid=$type[$i]['type_id']; 
            //先显示订
            /* $sql1="select cr_food.shop_id,cr_food.food_id,cr_shopcart.num,cr_food.pic,cr_food.price,cr_food.intro,cr_food.foodname from cr_food left join  cr_type on cr_food.type_id=cr_type.type_id AND cr_food.shop_id=cr_type.shop_id left join cr_shopcart on cr_food.food_id=cr_shopcart.food_id where cr_type.type_id='$tid' ";*/
             $sql1="
             select cr_food.shop_id,cr_food.food_id,cr_shopcart.num,cr_shopcart.user_id,cr_food.pic,cr_food.price,cr_food.intro,cr_food.foodname from cr_food left join  cr_type on cr_food.type_id=cr_type.type_id AND cr_food.shop_id=cr_type.shop_id left join (select * from cr_shopcart where user_id=$uid) cr_shopcart on cr_food.food_id=cr_shopcart.food_id where cr_type.type_id='$tid'";
             $tfood[$i]=\think\Db::name('')->query($sql1);
             
        } 
        //得到购物车总量
        $sum=\think\Db::name('shopcart')->where("user_id=$uid AND shop_id=$shop_id")->sum('num');
        //得到别选菜的ID
        $ID=\think\Db::name('shopcart')->where("user_id=$uid AND shop_id=$shop_id")->select();
        $priceList=array();
        for ($i=0; $i < sizeof($ID) ; $i++) { 
          $food_id=$ID[$i]['food_id'];
         
         $priceList[$i]=\think\Db::name('food')->query("select price from cr_food where food_id=$food_id");
        }  
        //获取总价
        $count=0;
        for ($i=0; $i <sizeof($priceList) ; $i++) { 
        
        for ($j=0; $j <sizeof($priceList[$i]) ; $j++) { 
         $price=$priceList[$i][$j]['price'];
         $count+=$price;
        }
        
        }
        //得到店铺的运费
        $shopFee=Db::name('dining')->where("shop_id=$id")->column('fei');
        $shopFee1=$shopFee[0];
        //得到提交订单菜品信息
        $orderList=Db::name('')->query("select * from cr_shopcart  s  inner join cr_food f on f.food_id=s.food_id where s.shop_id='$id' AND s.user_id='$uid'");
        //运费+菜品总价格
         $orderSum=$count+$shopFee1;
        $this->assign(array(
          "UUID"=>$uid,
          'shop_id'=>$shop_id,
          'orderSum'=>$orderSum,
          'shopFee1'=>$shopFee1,
          'orderList'=>$orderList,
          'userInfo'=>$userInfo,
          'sum'=>$sum
          ));
       
      }
       
         $this->assign(array(
          'shop_id'=>$shop_id,
          ));
        //echo \think\Db::name('')->getLastSql();
        $this->assign("count",$count);
        $this->assign("shopPic",$shopPic[0]);
        $this->assign("tfood",$tfood);
        $this->assign("type",$type);
        $this->assign("plist",$list);
        $this->assign("shopinfo",$shopinfo);
       return $this->fetch();
    }
  

    //提交订单
    public function submitOrder($shop_id)
    {

       //得到用户的session登陆信息 
      if(session('id')==null) {
       $uid=null;
       $this->error('您没有登录','index/index');
       return;
       }
      else
      {
         $uid=session('id');
         $re=Db::name('shopcart')->where("user_id='$uid' AND shop_id='$shop_id'")->find();
         if($re==null)
         {
          $this->error('傻了吧，你没选菜呢');
          return;
         }
      }
      //
       $orderList=Db::name('')->query("select * from cr_shopcart  s  inner join cr_food f on f.food_id=s.food_id where s.shop_id='$shop_id' AND s.user_id='$uid'");
       //生成订单 
       $rand=rand(11111,99999);
       $time=time();
       $order_id=$time.$rand;
       $map=array();
       for ($i=0; $i <sizeof($orderList) ; $i++) { 
            $shopcart_id=$orderList[$i]['id'];
            $priceSum=0;
            $priceSum=$orderList[$i]['num']*$orderList[$i]['price'];
            $map['order_id']=$order_id;
            $map['food_id']=$orderList[$i]['food_id'];
            $map['shop_id']=$orderList[$i]['shop_id'];
            $map['num']=$orderList[$i]['num'];
            $map['user_id']=$uid;
            $map['sum']=$priceSum;
            $re=Db::name('order')->insert($map);
            Db::name('shopcart')->delete($shopcart_id);

       }
       ////生成room表
       $ad=Db::name('users')->where("id='$uid'")->column('address');
       $address=$ad[0];
       $data=array();
       $data['suggesttime']=input('post.suggesttime');
       $data['isorder']=input('post.isOrder');
       $data['comment']=input('post.comment');
       $data["ordertime"]=date('Y-m-d h:i:s');
       $data['shop_id']=$shop_id;
       $data['uid']=$uid;
       $data['state']=0;
       $data['takeoutaddr']=$address;
       $data['order_id']=$order_id;
      if(Db::name('room')->insert($data))
      {
        $this->success("订单提交成功");
        //echo 1;
      }
      else{
        $this->error("订单提交失败");
        echo 0;
      } 
       
    }

     //热门（人气）餐厅列表（按订单数降序排列）
     public function hotshoplists()
    {
        //0元配送（按配送费为0及订单数降序排列）
        $feeList=\think\Db::name('dining')
        ->alias('d')
        ->join('cr_order o','d.shop_id=o.shop_id')
        ->field('d.shopname,d.shop_id,d.pic')
        ->group('o.shop_id')
        ->order('sum(o.num) desc')
        ->where('d.fei=0')
        ->limit(5)
        ->select();
        //按评分排名
        $levelList=\think\Db::name('dining')->order('level desc')->limit(5)->select();
        //热门餐厅,无销量餐厅没有显示
        $p=6;
        $list=\think\Db::name('dining')
        ->alias('d')
        ->join('cr_order o','d.shop_id=o.shop_id')
        ->field('d.shopname,d.level,d.obserave,d.shop_id,d.fei,d.pic,sum(o.num) s')
        ->group('o.shop_id')
        ->order('sum(o.num) desc')
        ->paginate($p);
        $page=$list->render();
        $this->assign('levelList',$levelList);  
        $this->assign('list',$list); 
        $this->assign('page',$page);   
        $this->assign('feeList',$feeList);   
        return $this->fetch();
    }


     // 新进餐厅列表（按时间降序排列）
     public function newshoplists()
     {

        //销量最高
        $topList=\think\Db::name('dining')
        ->alias('d')
        ->join('cr_order o','d.shop_id=o.shop_id')
        ->field('d.shopname,d.shop_id,d.pic')
        ->group('o.shop_id')
        ->order('sum(o.num) desc')
        ->limit(5)
        ->select();
        //最新餐厅列表
         $newshop = \think\Db::name('dining')->order('createtime desc')->paginate(6);
         //0元配送
         $zero=\think\Db::name('dining')->where("fei='0'")->order('createtime desc')->field('pic,shopname,shop_id')->limit(5)->select();
         $this->assign('zero',$zero);
         $this->assign('topList',$topList);
         $this->assign('newshop',$newshop);
         return $this->fetch();
    }

    public  function  order(){
       $user = session('id');//获取用户ID
      if (request()->isPost()){
      }
    }
}
